import * as types from './actionTypes';
import Util from '../common/utils';
import { hex_sha1 } from '../common/sha1';

export let getLoginInfo = (key) => {

    return dispatch => {
        // 请求登录信息
        dispatch(LoginInfo());
        return Util.getStorage(key, (res) => {
            dispatch(receiveLoginInfo(res));
        }, (err) => {
            dispatch(receiveLoginInfo({username : '',password : ''}));
        })
    }
};

export let LoginInfo = () => {
	return {
		'type' : types.FETCH_LOGIN_INFO,
	}
};

export let receiveLoginInfo = (login) => {
	return {
		'type' : types.RECEIVE_LOGIN_INFO,
		'login' : login
	}
};


export let login = (username, password) => {

    let url = global.U + '/api/uc/uc/userLoginService/login';

    return dispatch => {

        console.log('密码');
        console.log(hex_sha1(password));

        dispatch(checkLogin());
        return Util.post(url, {'username' : username, 'password' : hex_sha1(password)}, (response) => {
            console.log('login返回数据');
            console.log(response);
            dispatch(receiveLogin(response));
        }, (error) => {
            console.log('Fetch login error: ' + error);
            dispatch(receiveLogin({}));
        });

    }

}


export let checkLogin = () => {
    return {
        'type' : types.CHECK_LOGIN,
        'loading' : true,
    }
}


export let receiveLogin = (res) => {
    return {
        'type' : types.RECEIVE_LOGIN,
        'login' : res,
        'loading' : false,
    }
}